"""
追踪管理API路由
"""
from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, Query, status
from fastapi.responses import JSONResponse

from app.schemas.tracking import (
    TrackingDeviceCreate, TrackingDeviceUpdate, TrackingDeviceResponse, TrackingListResponse,
    LocationHistoryCreate, LocationHistoryResponse, LocationListResponse,
    GeofenceAreaCreate, GeofenceAreaUpdate, GeofenceAreaResponse,
    GeofenceEventResponse, RealTimeLocationResponse
)
from app.schemas.base import ResponseModel
from app.services.tracking_service import TrackingDeviceService, LocationService, GeofenceService
from app.utils.dependencies import get_current_user
from app.models.user import User

router = APIRouter(prefix="/tracking", tags=["追踪管理"])


# 追踪设备相关路由
@router.post(
    "/devices",
    response_model=TrackingDeviceResponse,
    status_code=status.HTTP_201_CREATED,
    summary="创建追踪设备"
)
async def create_tracking_device(
    device_data: TrackingDeviceCreate,
    current_user: User = Depends(get_current_user)
):
    """创建追踪设备"""
    return await TrackingDeviceService.create_device(device_data)


@router.get(
    "/devices/{device_id}",
    response_model=TrackingDeviceResponse,
    summary="获取追踪设备详情"
)
async def get_tracking_device(device_id: int):
    """获取追踪设备详情"""
    return await TrackingDeviceService.get_device(device_id)


@router.put(
    "/devices/{device_id}",
    response_model=TrackingDeviceResponse,
    summary="更新追踪设备"
)
async def update_tracking_device(
    device_id: int,
    device_data: TrackingDeviceUpdate,
    current_user: User = Depends(get_current_user)
):
    """更新追踪设备"""
    return await TrackingDeviceService.update_device(device_id, device_data)


@router.delete(
    "/devices/{device_id}",
    response_model=ResponseModel,
    summary="删除追踪设备"
)
async def delete_tracking_device(
    device_id: int,
    current_user: User = Depends(get_current_user)
):
    """删除追踪设备"""
    success = await TrackingDeviceService.delete_device(device_id)
    return ResponseModel(
        success=success,
        message="追踪设备删除成功" if success else "追踪设备删除失败"
    )


@router.get(
    "/devices",
    response_model=TrackingListResponse,
    summary="获取追踪设备列表"
)
async def list_tracking_devices(
    page: int = Query(default=1, ge=1, description="页码"),
    size: int = Query(default=20, ge=1, le=100, description="每页数量"),
    device_type: Optional[str] = Query(default=None, description="设备类型"),
    status: Optional[str] = Query(default=None, description="状态"),
    cargo_id: Optional[int] = Query(default=None, description="关联货物ID"),
    equipment_id: Optional[int] = Query(default=None, description="关联装备ID")
):
    """获取追踪设备列表"""
    devices, total = await TrackingDeviceService.list_devices(
        page=page,
        size=size,
        device_type=device_type,
        status=status,
        cargo_id=cargo_id,
        equipment_id=equipment_id
    )
    
    pages = (total + size - 1) // size
    
    return TrackingListResponse(
        items=devices,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


# 位置相关路由
@router.post(
    "/locations",
    response_model=LocationHistoryResponse,
    status_code=status.HTTP_201_CREATED,
    summary="记录位置信息"
)
async def record_location(
    location_data: LocationHistoryCreate,
    current_user: User = Depends(get_current_user)
):
    """记录位置信息"""
    return await LocationService.record_location(location_data)


@router.get(
    "/devices/{device_id}/locations",
    response_model=LocationListResponse,
    summary="获取设备位置历史"
)
async def get_device_locations(
    device_id: int,
    start_time: Optional[datetime] = Query(default=None, description="开始时间"),
    end_time: Optional[datetime] = Query(default=None, description="结束时间"),
    page: int = Query(default=1, ge=1, description="页码"),
    size: int = Query(default=20, ge=1, le=100, description="每页数量")
):
    """获取设备位置历史"""
    locations, total = await LocationService.get_device_locations(
        device_id=device_id,
        start_time=start_time,
        end_time=end_time,
        page=page,
        size=size
    )
    
    pages = (total + size - 1) // size
    
    return LocationListResponse(
        items=locations,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


@router.get(
    "/locations/realtime",
    response_model=List[RealTimeLocationResponse],
    summary="获取实时位置"
)
async def get_realtime_locations():
    """获取所有设备的实时位置"""
    return await LocationService.get_latest_locations()


# 地理围栏相关路由
@router.post(
    "/geofences",
    response_model=GeofenceAreaResponse,
    status_code=status.HTTP_201_CREATED,
    summary="创建地理围栏"
)
async def create_geofence(
    geofence_data: GeofenceAreaCreate,
    current_user: User = Depends(get_current_user)
):
    """创建地理围栏"""
    return await GeofenceService.create_geofence(geofence_data)


@router.put(
    "/geofences/{geofence_id}",
    response_model=GeofenceAreaResponse,
    summary="更新地理围栏"
)
async def update_geofence(
    geofence_id: int,
    geofence_data: GeofenceAreaUpdate,
    current_user: User = Depends(get_current_user)
):
    """更新地理围栏"""
    return await GeofenceService.update_geofence(geofence_id, geofence_data)


@router.delete(
    "/geofences/{geofence_id}",
    response_model=ResponseModel,
    summary="删除地理围栏"
)
async def delete_geofence(
    geofence_id: int,
    current_user: User = Depends(get_current_user)
):
    """删除地理围栏"""
    success = await GeofenceService.delete_geofence(geofence_id)
    return ResponseModel(
        success=success,
        message="地理围栏删除成功" if success else "地理围栏删除失败"
    )


@router.get(
    "/geofences",
    response_model=List[GeofenceAreaResponse],
    summary="获取地理围栏列表"
)
async def list_geofences(
    page: int = Query(default=1, ge=1, description="页码"),
    size: int = Query(default=20, ge=1, le=100, description="每页数量"),
    fence_type: Optional[str] = Query(default=None, description="围栏类型"),
    is_enabled: Optional[bool] = Query(default=None, description="是否启用")
):
    """获取地理围栏列表"""
    geofences, total = await GeofenceService.list_geofences(
        page=page,
        size=size,
        fence_type=fence_type,
        is_enabled=is_enabled
    )
    
    return geofences


@router.post(
    "/geofences/check",
    response_model=List[GeofenceEventResponse],
    summary="检查地理围栏违规"
)
async def check_geofence_violations(
    device_id: int,
    latitude: float,
    longitude: float,
    current_user: User = Depends(get_current_user)
):
    """检查地理围栏违规"""
    return await GeofenceService.check_geofence_violation(device_id, latitude, longitude)


@router.get(
    "/statistics/summary",
    summary="获取追踪统计摘要"
)
async def get_tracking_statistics():
    """获取追踪统计摘要"""
    from app.models.tracking import TrackingDevice, LocationHistory, GeofenceArea, GeofenceEvent
    
    try:
        # 总设备数量
        total_devices = await TrackingDevice.all().count()
        
        # 按状态统计设备
        active_devices = await TrackingDevice.filter(status="active").count()
        inactive_devices = await TrackingDevice.filter(status="inactive").count()
        offline_devices = await TrackingDevice.filter(status="offline").count()
        
        # 按设备类型统计
        gps_devices = await TrackingDevice.filter(device_type="gps").count()
        rfid_devices = await TrackingDevice.filter(device_type="rfid").count()
        beacon_devices = await TrackingDevice.filter(device_type="beacon").count()
        sensor_devices = await TrackingDevice.filter(device_type="sensor").count()
        
        # 位置记录统计
        total_locations = await LocationHistory.all().count()
        
        # 地理围栏统计
        total_geofences = await GeofenceArea.all().count()
        enabled_geofences = await GeofenceArea.filter(is_enabled=True).count()
        
        # 围栏事件统计
        total_events = await GeofenceEvent.all().count()
        unprocessed_events = await GeofenceEvent.filter(is_processed=False).count()
        
        return {
            "device_statistics": {
                "total": total_devices,
                "active": active_devices,
                "inactive": inactive_devices,
                "offline": offline_devices
            },
            "device_type_statistics": {
                "gps": gps_devices,
                "rfid": rfid_devices,
                "beacon": beacon_devices,
                "sensor": sensor_devices
            },
            "location_statistics": {
                "total_records": total_locations
            },
            "geofence_statistics": {
                "total": total_geofences,
                "enabled": enabled_geofences,
                "total_events": total_events,
                "unprocessed_events": unprocessed_events
            }
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取统计数据失败"
        )
